import express from 'express';
import cors from 'cors';
import winston from 'winston';
import multer from 'multer';
import path from 'path';
import fs from 'fs';

// 配置日志
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [new winston.transports.Console()]
});

const app = express();

// 创建uploads目录
const uploadsDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置multer文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB
  },
  fileFilter: (req, file, cb) => {
    // 检查文件类型
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图像文件'));
    }
  }
});

// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 模拟用户数据
const users = {
  admin: {
    id: 1,
    username: 'admin',
    password: 'Admin123',
    real_name: '系统管理员',
    role: 3,
    department: '信息科',
    title: '系统管理员'
  }
};

// 模拟JWT
const createToken = (user) => {
  return 'mock_token_' + user.id + '_' + Date.now();
};

// 请求日志
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path}`);
  next();
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'API运行正常',
    data: { timestamp: new Date().toISOString() }
  });
});

// 登录
app.post('/api/doctors/login', (req, res) => {
  const { username, password } = req.body;

  logger.info('登录请求:', { username, password });

  if (!username || !password) {
    return res.status(400).json({
      success: false,
      message: '用户名和密码不能为空'
    });
  }

  const user = users[username];
  if (!user || user.password !== password) {
    return res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }

  const token = createToken(user);
  res.json({
    success: true,
    message: '登录成功',
    data: {
      token,
      doctor: {
        doctor_id: user.id,
        username: user.username,
        real_name: user.real_name,
        role: user.role,
        department: user.department,
        title: user.title,
        role_name: user.role === 3 ? '系统管理员' : '医生'
      }
    }
  });
});

// 获取用户信息
app.post('/api/doctors/info', (req, res) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token || !token.startsWith('mock_token_')) {
    return res.status(401).json({
      success: false,
      message: '无效的令牌'
    });
  }

  // 从token中提取用户ID
  const userId = parseInt(token.split('_')[2]);
  const user = Object.values(users).find(u => u.id === userId);

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在'
    });
  }

  res.json({
    success: true,
    message: '获取用户信息成功',
    data: {
      doctor_id: user.id,
      username: user.username,
      real_name: user.real_name,
      role: user.role,
      department: user.department,
      title: user.title,
      role_name: user.role === 3 ? '系统管理员' : '医生'
    }
  });
});

// 模拟任务提交
let taskIdCounter = 1;
app.post('/api/scoring/submit', upload.single('image'), (req, res) => {
  const { patient_code, clinical_text } = req.body;

  // 模拟文件处理
  const imageFile = req.file;
  if (!imageFile) {
    return res.status(400).json({
      success: false,
      message: '请上传内镜图像'
    });
  }

  const taskId = taskIdCounter++;

  // 模拟异步AI分析
  setTimeout(() => {
    logger.info(`任务 ${taskId} AI分析完成`);
  }, 3000);

  res.json({
    success: true,
    message: '任务提交成功，正在进行AI分析',
    data: {
      task_id: taskId,
      patient_code,
      status: 1, // 准备中
      created_at: new Date().toISOString()
    }
  });
});

// 模拟任务状态查询
const taskResults = new Map();
app.post('/api/scoring/result', (req, res) => {
  const { task_id } = req.body;

  let result = taskResults.get(task_id);

  if (!result) {
    // 首次查询，返回初始状态
    result = {
      task_info: {
        task_id,
        patient_code: 'TEST001',
        status: 2, // 分析中
        created_at: new Date().toISOString()
      },
      ai_result: null
    };
    taskResults.set(task_id, result);

    // 模拟分析完成
    setTimeout(() => {
      result.task_info.status = 3; // 已完成
      result.ai_result = {
        score: Math.floor(Math.random() * 13),
        severity: Math.floor(Math.random() * 4) + 1,
        severity_name: ['缓解期', '轻度', '中度', '重度'][Math.floor(Math.random() * 4)],
        confidence: Math.floor(Math.random() * 31) + 70,
        analysis_details: 'AI模拟分析：观察到黏膜充血、水肿，伴有血管纹理消失和糜烂表现。病变范围涉及结肠多个节段，建议结合临床症状进行综合评估。',
        model_version: 'EndoSight-UC-v1.0.0',
        created_at: new Date().toISOString()
      };
    }, 5000);
  }

  res.json({
    success: true,
    message: '获取任务结果成功',
    data: result
  });
});

// 任务列表
app.post('/api/scoring/list', (req, res) => {
  const { page = 1, limit = 10, status = null } = req.body;

  const mockTasks = [];
  for (let i = 1; i <= 5; i++) {
    mockTasks.push({
      task_id: i,
      patient_code: `TEST${String(i).padStart(3, '0')}`,
      status: Math.floor(Math.random() * 4) + 1,
      created_at: new Date(Date.now() - i * 86400000).toISOString(),
      completed_at: i <= 2 ? new Date(Date.now() - i * 86400000 + 3600000).toISOString() : null
    });
  }

  res.json({
    success: true,
    message: '获取任务列表成功',
    data: {
      tasks: mockTasks,
      total: mockTasks.length,
      page,
      limit
    }
  });
});

// 启动服务器
const PORT = 4002;
app.listen(PORT, () => {
  logger.info(`🚀 简化服务器启动成功! 端口: ${PORT}`);
  logger.info(`📝 测试账号: admin / Admin123`);
});

export default app;